/*
 * @Description: 编辑排序规则弹窗组件
 * @Author: Rfan
 * @Date: 2022-03-07 11:24:01
 * @LastEditTime: 2023-01-12 16:26:14
 */

import { useEffect, useState } from 'react';
import { Button, Form, Modal } from 'antd';
import { fetchMetadata } from '@/api/metadata';
import FormItem from './common/FormItem';
import { QUERY_METADATA_SORT } from '@/view/system/Metadata/constants';
import { useSortContext } from '../../contexts/SortContext';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { IMetadata } from '@/interfaces/metadata';

interface EditDialogProps extends ICommonDialog {
  data: any;
}

const EditDialog: FC<EditDialogProps> = (props) => {
  const { visible, data, onClose } = props;
  const { selectAT, selectLevel, editSortingFunc } = useSortContext();
  const [form] = Form.useForm();
  // 元数据列表
  const [fieldList, setFieldList] = useState<IMetadata[]>([]);

  useEffect(() => {
    if (visible) {
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_SORT,
        coordinate: {
          atType: selectAT.atType,
          atCode: selectAT.atCode,
          level: selectLevel.level
        }
      };
      fetchMetadata(fieldQuery).then((res) => {
        setFieldList(res.data);
      });
      form.setFieldsValue(data.rule);
    }
  }, [visible]);
  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 编辑排序方法
  const onFinish = (values: any) => {
    editSortingFunc({ ...data.rule, ...values }).then(() => {
      onCancel();
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="编辑排序字段"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button
          key="back"
          onClick={() => {
            onCancel();
          }}
        >
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={() => {
            submitFunc();
          }}
        >
          保存
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <FormItem fieldList={fieldList} />
      </Form>
    </Modal>
  );
};

export default EditDialog;
